#!/usr/bin/python3
# coding=UTF-8

import os
import uvicorn
from fastapi import FastAPI
from fastapi.openapi.docs import (
    get_redoc_html,
    get_swagger_ui_html,
    get_swagger_ui_oauth2_redirect_html,
)
from fastapi.staticfiles import StaticFiles
from fastapi.openapi.utils import get_openapi
from fastapi.responses import JSONResponse
from services.routes.general import general
from services.routes.student import student
from tortoise.contrib.fastapi import register_tortoise
from orm.tortoise_orm import TORTOISE_ORM

app = FastAPI(title="测试辅助工具箱", description="边学边增加新功能", docs_url=None, redoc_url=None)
app.openapi_version = "3.0.0"

# 重置FastApi 提供的读取静态文件的方法
root_dir = os.path.dirname(os.path.abspath(__file__))
static_dir = os.path.join(root_dir, "./statics")
temp_dir = os.path.join(root_dir, "./templates")
app.mount(
    "/statics", StaticFiles(directory=static_dir), name="statics"
)


# 可以同时挂在多个静态文件夹
# app.mount("/temps", StaticFiles(directory=temp_dir))

def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    openapi_schema = get_openapi(
        # title="测试辅助工具箱-持续更新",
        # description="边学边用FastApi",
        routes=app.routes,
    )
    # 添加服务器地址
    openapi_schema["servers"] = [{"url": "http://127.0.0.1:5555"}]
    app.openapi_schema = openapi_schema
    return app.openapi_schema


@app.get("/openapi.json", include_in_schema=False)
async def get_custom_openapi():
    return JSONResponse(custom_openapi())


@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
    return get_swagger_ui_html(
        # openapi_url=app.openapi_url,
        openapi_url="/openapi.json",
        title=app.title + "-Swagger UI",
        oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
        swagger_js_url="/statics/swagger-ui/swagger-ui-bundle.js",
        swagger_css_url="/statics/swagger-ui/swagger-ui.css",
    )


@app.get(app.swagger_ui_oauth2_redirect_url, include_in_schema=False)
async def swagger_ui_redirect():
    return get_swagger_ui_oauth2_redirect_html()


@app.get("/redocs", include_in_schema=False)
async def redoc_html():
    return get_redoc_html(
        # openapi_url=app.openapi_url,
        openapi_url="/openapi.json",
        title=app.title + "-ReDoc",
        redoc_js_url="/statics/redoc/bundles/redoc.standalone.js",
    )


register_tortoise(app=app, config=TORTOISE_ORM)

# 引用子服务的路由
app.include_router(general, prefix="/api/learn", tags=["自我学习"])
app.include_router(student, prefix="/api/student", tags=["学生管理"])

if __name__ == "__main__":
    uvicorn.run(
        "main:app", host="127.0.0.1", port=5555, log_level="info", reload=True
    )
